# Created with PyCharm.
# Coding UTF-8
# @Version Python 3.8

# @author GeekChunky
# @Email caiyoupeng00@outlook.com

# @Date 2021/11/23
# @CreatTime 19:45

'''
Documentation comments:
    Python自动化新建任务ID（V2.0 Beta）
    （涵盖了切换窗口之跳转iframe的知识点）
    （模拟键盘操作）
'''

# Now Write Down Your Python Code in Editor...
# Wish You Happy Everyday !

# import msvcrt
# 导入unittest
import unittest
# 从数据驱动导入ddt,unpack,data
from ddt import ddt, unpack, data
# 导入Webdriver
from selenium import webdriver
# 导入By模块
from selenium.webdriver.common.by import By
# 导入键盘映射模块
from selenium.webdriver.common.keys import Keys
# 导入选择器模块
from selenium.webdriver.support.select import Select
# 导入暂停模块
from time import sleep
# 导入datetime模块
from datetime import timedelta, date
# 导入警示模块
from warnings import simplefilter
# 导入系统控件
from sys import exit
# 导入raw_input
from pip._vendor.distlib.compat import raw_input
# 导入msedge服务插件
from msedge.selenium_tools import Edge, EdgeOptions

'''
# 导入
import string
# 导入随机模块
import random
key_name = string.ascii_letters
# 大写string.ascii_uppercase
# 小写string.ascii_lowercase
taskName = random.choice(key_name)
print(taskName)
'''

print('2017四和天地资产管理实训系统自动化工具（Edge版 V3.0）')
print('制作人：@GeekChunky')
print('\nThis automation plug-in is based on \"WebDriver\" configured \"Google Cores\" browser.\n')

startProgram = raw_input('Press \'Enter\' into the program')

# 提示输入任务名称
while True:
    taskName = input('请输入任务名称：')
    if taskName != '':
        break
    print('任务名称必填！请重新输入！')

# 获取当天日期为开始日期
startTime = str(date.today())

# 计算结束时间
overTime = str(date.today())

# 任务要求
taskNeed = taskName + 'CreatedFromPythonSeleniumScript'

# 相关数据
account = 'softtest2018'
password = 'aaa'

# 写入
rows_zclb = [('资产数据01', 'Test01'), ('资产数据02', 'Test02'), ('资产数据03', 'Test03')]
rows_pinpai = [('品牌数据01', 'Test01'), ('品牌数据02', 'Test02'), ('品牌数据03', 'Test03')]
rows_baofei = [('报废数据01', 'Test01'), ('报废数据02', 'Test02'), ('报废数据03', 'Test03')]
rows_bumen = [('部门数据01', 'Test01'), ('部门数据02', 'Test02'), ('部门数据03', 'Test03')]

# 提示语句
print()
sleep(1)
print('接受成功！正在获取其他相关数据...')
sleep(1)
print('已就绪...')
print('开始生成...')

# 开始Edge设置
options = EdgeOptions()
# 使用谷歌内核
options.use_chromium = True
# 浏览器可执行文件绝对路径
options.binary_location = r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"
# 浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败
options.add_argument("--headless")
# 谷歌文档提到需要加上这个属性来规避bug
options.add_argument("disable-gpu")
# 启动驱动
driver = Edge(executable_path=r"C:\Users\caiyo\AppData\Local\Programs\Python\Python38\BroswerDriver\msedgedriver.exe",
              options=options)
# get获取URL
driver.get('http://192.168.1.251/')
# 添加智能等待时间
driver.implicitly_wait(10)
# 输入用户名
driver.find_element(By.XPATH, '//*[@id="loginName"]').send_keys(account)
# 输入密码
driver.find_element(By.XPATH, '//*[@id="pwd"]').send_keys(password)
# 添加暂停时间1s
sleep(1)
# 点击登录
driver.find_element(By.XPATH, '//*[@id="fmedit"]/div/div[5]/input').click()
# 添加暂停时间1s
sleep(1)
# 点击任务列表菜单栏
driver.find_element(By.XPATH, '//*[@id="tabmenu_task"]/a').click()
# 点击新增任务按钮
driver.find_element(By.CSS_SELECTOR,
                    'body > div.border_bg_withbtn > div.content_bg > div.add_submit > div > input').click()
# 输入任务名称
driver.find_element(By.CSS_SELECTOR, '#task_title').send_keys(taskName)
# 软件名称下拉框选择器选择
Select(driver.find_element(By.CSS_SELECTOR, '#softId')).select_by_visible_text('资产管理系统软件(B/S和安卓)')
# 添加暂停时间1s
sleep(1)
# 任务种类下拉框选择器选择
Select(driver.find_element(By.CSS_SELECTOR, '#taskTypeId')).select_by_visible_text('B/S结构功能测试')
# 勾选分配班级
driver.find_element(By.XPATH, '//*[@id="fmedit"]/table/tbody/tr[4]/td[2]/div/input[1]').click()
driver.find_element(By.XPATH, '//*[@id="fmedit"]/table/tbody/tr[4]/td[2]/div/input[2]').click()
driver.find_element(By.XPATH, '//*[@id="fmedit"]/table/tbody/tr[4]/td[2]/div/input[3]').click()
# 输入开始时间
driver.find_element(By.XPATH, '//*[@id="beginDate"]').send_keys(startTime)
# 输入结束时间
driver.find_element(By.XPATH, '//*[@id="endDate"]').send_keys(overTime)
# 定位到该iframe框架
element = driver.find_element(By.XPATH, '//*[@id="cke_1_contents"]/iframe')
# 跳入iframe框架
driver.switch_to.frame(element)
# 添加任务需求
driver.find_element(By.XPATH, '/html/body').send_keys(taskNeed)
# 跳回最外层页面
driver.switch_to.default_content()
# 点击确定按钮
driver.find_element(By.XPATH, '//*[@id="btnok"]').click()
# 添加暂停时间5s
sleep(4)
# 点击确定按钮关闭弹窗
driver.find_element(By.XPATH, '//*[@id="popCloseBtn"]').click()
# 获取最新的任务ID
text = driver.find_elements_by_tag_name("td")[1].text
# 将最新的任务ID发送到输入框
driver.find_element(By.XPATH, '//*[@id="taskId"]').send_keys(text)
# 将输入框全选
driver.find_element(By.XPATH, '//*[@id="taskId"]').send_keys(Keys.CONTROL, 'a')
# 将输入框内容剪切
driver.find_element(By.XPATH, '//*[@id="taskId"]').send_keys(Keys.CONTROL, 'x')
# TODO:关闭当前标签页(无法关闭，没办法节省资源)
# driver.close()
# 生成完毕
print('\n生成完毕\n本次生成的任务ID为：' + text + '\n生成的任务ID仅供当天使用')
print('如无需初始化数据，即可使用xg02用户登录')
sleep(1)
print('任务ID已自动获取至剪贴板')
print()
print('即将注入数据...')
print('建议：数据注入完成后再登录')
print('注入数据预计用时：15s')
sleep(1)
# 载入新标签页
driver.execute_script("window.open('');")
# 操作转至新标签页
driver.switch_to.window(driver.window_handles[1])
# 最小化窗口
driver.minimize_window()
# Get资产管理系统
driver.get('http://192.168.1.251/bsams')
# 将获取到剪贴版的任务ID输入输入框
driver.find_element(By.XPATH, '//*[@id="taskId"]').send_keys(Keys.CONTROL, 'v')
# 输入用户名
driver.find_element(By.XPATH, '//*[@id="loginName"]').send_keys('xg01')
# 输入密码
driver.find_element(By.XPATH, '//*[@id="password"]').send_keys('xg01')
# 输入验证码
driver.find_element(By.XPATH, '//*[@id="vericode"]').send_keys('shtd')
# 点击登录
driver.find_element(By.XPATH, '//*[@id="fmedit"]/div[2]/div[6]/input').click()


# ddt数据驱动注入数据
@ddt
class test_addData(unittest.TestCase):

    @classmethod
    # 去除警示信息
    def setUpClass(cls):
        simplefilter('ignore', ResourceWarning)
        simplefilter('ignore', DeprecationWarning)

    @data(*rows_zclb)
    @unpack
    def test_zclb(self, name, num):
        # 点击资产类别菜单栏
        driver.find_element(By.LINK_TEXT, '资产类别').click()
        # 点击新增
        driver.find_element(By.XPATH, '/html/body/div[2]/div/div[2]/div[2]/div[1]/div/input').click()
        # 输入名称
        driver.find_element(By.XPATH, '//*[@id="title"]').send_keys(name)
        # 输入编码
        driver.find_element(By.XPATH, '//*[@id="code"]').send_keys(num)
        # 点击确定
        driver.find_element(By.XPATH, '//*[@id="cboxLoadedContent"]/div/div[3]/a[2]').click()
        # 等待弹窗1s
        sleep(1)
        # 确定弹窗
        driver.switch_to_alert().accept()

    @data(*rows_pinpai)
    @unpack
    def test_pinpai(self, a, b):
        # 点击品牌菜单栏
        driver.find_element(By.LINK_TEXT, '品牌').click()
        # 点击新增
        driver.find_element(By.XPATH, '/html/body/div[2]/div/div[2]/div[2]/div[1]/div/input').click()
        # 输入名称
        driver.find_element(By.XPATH, '//*[@id="title"]').send_keys(a)
        # 输入编码
        driver.find_element(By.XPATH, '//*[@id="code"]').send_keys(b)
        # 点击确定
        driver.find_element(By.XPATH, '//*[@id="cboxLoadedContent"]/div/div[3]/a[2]').click()
        # 等待弹窗1s
        sleep(1)
        # 去除弹窗
        driver.switch_to_alert().accept()

    @data(*rows_bumen)
    @unpack
    def test_bumen(self, a, b):
        # 点击部门管理菜单栏
        driver.find_element(By.LINK_TEXT, '部门管理').click()
        # 点击新增
        driver.find_element(By.XPATH, '/html/body/div[2]/div/div[2]/div[2]/div[1]/div/input').click()
        # 输入名称
        driver.find_element(By.XPATH, '//*[@id="title"]').send_keys(a)
        # 输入编码
        driver.find_element(By.XPATH, '//*[@id="code"]').send_keys(b)
        # 点击确定
        driver.find_element(By.XPATH, '//*[@id="cboxLoadedContent"]/div/div[3]/a[2]').click()
        # 等待弹窗1s
        sleep(1)
        # 去除弹窗
        driver.switch_to_alert().accept()

    @data(*rows_baofei)
    @unpack
    def test_baofei(self, a, b):
        # 点击报废方式菜单栏
        driver.find_element(By.LINK_TEXT, '报废方式').click()
        # 点击新增
        driver.find_element(By.XPATH, '/html/body/div[2]/div/div[2]/div[2]/div[1]/div/input').click()
        # 输入名称
        driver.find_element(By.XPATH, '//*[@id="title"]').send_keys(a)
        # 输入编码
        driver.find_element(By.XPATH, '//*[@id="code"]').send_keys(b)
        # 点击确定
        driver.find_element(By.XPATH, '//*[@id="cboxLoadedContent"]/div/div[3]/a[2]').click()
        # 等待弹窗1s
        sleep(1)
        # 去除弹窗
        driver.switch_to_alert().accept()

    @classmethod
    def tearDownClass(cls):
        # 关闭浏览器
        driver.quit()
        # 在控制台中输出任务ID
        print('数据注入成功...')
        print()
        overProgram = raw_input('按回车键退出...')
        exit()


if __name__ == '__main__':
    unittest.main()
